package com.useeinfo.oa.open.api.maintainOrder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.CommonUtils;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.FacilityBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Facility;
import com.useeinfo.oa.modules.maintaining.biz.FacilityMaintainSnapBiz;
import com.useeinfo.oa.modules.maintaining.biz.MaintainOrderBiz;
import com.useeinfo.oa.modules.maintaining.biz.MaintainWorkLogBiz;
import com.useeinfo.oa.modules.maintaining.entity.FacilityMaintainSnap;
import com.useeinfo.oa.modules.maintaining.entity.MaintainOrder;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: YiYouFuPlatform
 * @author: Taogq
 * @createDate: 2019-01-07
 * @createTime: 09:29:24
 */
@RestController
@RequestMapping("/api/mobile/maintainOrder")
public class MaintainOrderAPI {
    @Autowired
    private MaintainOrderBiz maintainOrderBiz;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private MaintainWorkLogBiz maintainWorkLogBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private FacilityMaintainSnapBiz facilityMaintainSnapBiz;

    /**
     * 查询列表接口
     *
     * @param status    状态 0 待接单，1进行中 2 审核中 3 完成 4批量审核 5批量转单
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResultDto list(String status, String pageIndex, String pageSize, String searchParam,String date) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(null == systemUser){
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if(null == enterprise){
           return ResultUtil.error("企业信息有误");
        }
        return maintainOrderBiz.list(status, pageIndex,pageSize, systemUser, enterprise, searchParam,date);
    }


    /**
     * 工单详情
     *
     * @param id
     * @return
     */
    @RequestMapping("/detail")
    public ResultDto detail(String id) {
        return maintainOrderBiz.detail(id);
    }

    /**
     * 接单
     *
     * @param maintainOrderId
     * @return
     */
    @RequestMapping("/receive")
    public ResultDto receive(String maintainOrderId) {
        return maintainOrderBiz.receive(maintainOrderId);
    }

    /**
     * 到场
     */
    @RequestMapping("/present")
    public ResultDto present(String maintainOrderId, String longitude, String latitude) {
        return maintainOrderBiz.present(maintainOrderId, longitude, latitude);
    }

    /**
     * 打开新增一次性维保计划时 生成一个临时流水号 用来临时绑定设备和工艺信息
     */
    @RequestMapping(value = "/getMaintainOrderSerial")
    public ResultDto getMaintainOrderSerial(HttpServletRequest request) {
        return ResultUtil.success(CommonUtils.getRandomNumber(10));
    }


    /**
     * 新增一次性工单
     */
    @RequestMapping(value = "/addMaintainOrder")
    public ResultDto addMaintainOrder(@RequestParam(value = "orderName", required = false) String orderName,
                                      @RequestParam(value = "remindTime", required = false) String remindTime,
                                      @RequestParam(value = "endDateTime", required = false) String endDateTime,
                                      @RequestParam(value = "degree", required = false) String degree,
                                      @RequestParam(value = "type", required = false) String type,
                                      @RequestParam(value = "points", required = false) String points,
                                      @RequestParam(value = "completeAuditFlowId", required = false) String completeAuditFlowId,
                                      @RequestParam(value = "delayAuditFlowId", required = false) String delayAuditFlowId,
                                      @RequestParam(value = "cancelAuditFlowId", required = false) String cancelAuditFlowId,
                                      @RequestParam(value = "organizationId", required = false) String organizationId,
                                      @RequestParam(value = "serial", required = false) String serial,
                                      HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        MaintainOrder maintainOrder = new MaintainOrder();
        maintainOrder.setSerial(serial);
        maintainOrder.setOrderName(orderName);
        maintainOrder.setRemindTime(Integer.parseInt(remindTime));
        maintainOrder.setDegree(degree);
        maintainOrder.setType(type);
        maintainOrder.setPoints(Long.parseLong(points));
        maintainOrder.setOrderCode(enterprise == null ? StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6) : enterprise.getId() + "-" + StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6));
        List<String> completeAuditFlowIds = new ArrayList<>();
        if (StringUtils.isNotBlank(completeAuditFlowId)) {
            completeAuditFlowIds.add(cancelAuditFlowId);
        }
        List<String> delayAuditFlowIds = new ArrayList<>();
        if (StringUtils.isNotBlank(delayAuditFlowId)) {
            delayAuditFlowIds.add(delayAuditFlowId);
        }
        List<String> cancelAuditFlowIds = new ArrayList<>();
        if (StringUtils.isNotBlank(cancelAuditFlowId)) {
            cancelAuditFlowIds.add(cancelAuditFlowId);
        }
        List<String> organizationIds = new ArrayList<>();
        if (StringUtils.isNotBlank(organizationId)) {
            organizationIds.add(organizationId);
        }
        return maintainOrderBiz.save(maintainOrder, null, "", endDateTime, completeAuditFlowIds, delayAuditFlowIds, cancelAuditFlowIds, organizationIds, request);
    }

    /**
     * 参与人列表
     */
    @RequestMapping("/partnerList")
    @ResponseBody
    public ResultDto partnerList(String id) {
        return maintainOrderBiz.partnerList(id);
    }

    /**
     * 添加参与人
     */
    @RequestMapping("/addPartner")
    @ResponseBody
    public ResultDto addPartner(String maintainOrderId, String partnerArray) {
        return maintainOrderBiz.addPartner(maintainOrderId, partnerArray);
    }

    /**
     * 移除参与人
     */
    @RequestMapping("/removePartner")
    @ResponseBody
    public ResultDto removePartner(String id) {
        return maintainOrderBiz.removePartner(id);
    }

    /**
     * 参与人详情
     *
     * @param id
     * @param userId
     * @param tag
     * @return
     */
    @RequestMapping("/partnerDetail")
    @ResponseBody
    public ResultDto partnerDetail(String id, String userId, String tag) {
        return maintainOrderBiz.partnerDetail(id, userId, tag);
    }

    /**
     * 添加/修改工作日志
     */
    @RequestMapping("/addLog")
    public ResultDto addLog(String logId, String workLogCatId, String workLogLevelId, String workContent, String photos, String maintainOrderId) {
        return maintainWorkLogBiz.addLog(logId, workLogCatId, workLogLevelId, workContent, photos, maintainOrderId);
    }

    /**
     * 工作日志列表
     */
    @RequestMapping("/maintainWorkLogList")
    public ResultDto maintainWorkLogList(String pageIndex, String pageSize, String maintainOrderId) {
        return maintainWorkLogBiz.maintainWorkLogList(pageIndex, pageSize, maintainOrderId);
    }

    /**
     * 工作日志详情
     */
    @RequestMapping("/maintainWorkLogDetail")
    public ResultDto maintainWorkLogDetail(String maintainWorkLogId) {
        return maintainWorkLogBiz.maintainWorkLogDetail(maintainWorkLogId);
    }

    /**
     * 工作流程
     * @param maintainOrderId
     * @return
     */
    @RequestMapping("/workProgress")
    @ResponseBody
    public ResultDto workProgress(String maintainOrderId) {
        return maintainOrderBiz.workProgress(maintainOrderId);
    }


    /**
     * 关注/取消关注
     *
     * @param maintainOrderId
     * @param type
     * @return
     */
    @RequestMapping("/focus")
    public ResultDto focus(String maintainOrderId, Boolean type) {
        return maintainOrderBiz.focus(maintainOrderId, type);
    }

    /**
     * 添加备注
     */
    @RequestMapping("/addRemark")
    @ResponseBody
    public ResultDto addRemark(String contentId, String question, String measure, String remark) {
        return maintainOrderBiz.addRemark(contentId, question, measure, remark,null);
    }

    /**
     * 查询备注备注
     */
    @RequestMapping("/getRemark")
    @ResponseBody
    public ResultDto getRemark(String contentId) {
        return maintainOrderBiz.getRemark(contentId);
    }

    /**
     * 上传接口
     */
    @RequestMapping("/upload")
    @ResponseBody
    public ResultDto upload(MultipartFile file, String type) {
        return maintainOrderBiz.upload(file, type);
    }

    /**
     * 批量上传接口
     */
    @RequestMapping("/uploads")
    @ResponseBody
    public ResultDto uploads(@RequestParam(value = "file", required = false) MultipartFile[] file, String type,String moduleType) {
        return maintainOrderBiz.uploads(file, type,moduleType);
    }

    /**
     * 添加参与人查看更多
     */
    @RequestMapping("/partnerAddMore")
    @ResponseBody
    public ResultDto partnerAddMore(String contentArray, String maintainOrderId) {
        return maintainOrderBiz.partnerAddMore(contentArray, maintainOrderId);
    }

    /**
     * 维保异常报修
     */
    @RequestMapping("/addRepair")
    @ResponseBody
    public ResultDto addRepair(String maintainCode, String repairCode,String contentId) {
        return maintainOrderBiz.addRepair(maintainCode, repairCode,contentId);
    }

    /**
     * 字典下拉选接口
     */
    @RequestMapping("/getDictSelect")
    @ResponseBody
    public ResultDto getDictSelect(String typeCode) {
        return maintainOrderBiz.getDictSelect(typeCode);
    }

    /**
     * 关联维修单列表
     */
    @RequestMapping("/relateRepairOrder")
    @ResponseBody
    public ResultDto relateRepairOrder(String maintainCode) {
        return maintainOrderBiz.relateRepairOrder(maintainCode);
    }

    /**
     * 设备维保记录列表
     */
    @RequestMapping(value = "/maintainOrderListByFacility")
    public ResultDto maintainOrderListByFacility(@RequestParam(value = "facilityId", required = false) String facilityId,
                                                 @RequestParam(value = "pageIndex", required = false) String pageIndexParam,
                                                 @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                                 HttpServletRequest request){
        JSONObject data = new JSONObject();
        JSONArray rows = new JSONArray();
        data.put("rows",rows);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.success(data);
        }
        Facility facility = facilityBiz.findModel(StringConverters.ToLong(facilityId));
        if(facility==null){
            return ResultUtil.success(data);
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("facilityId",facilityId);
        List<FacilityMaintainSnap> facilityMaintainSnapList = facilityMaintainSnapBiz.findList(queryParam);
        String orderIds = "";
        if(CollectionUtils.isNotEmpty(facilityMaintainSnapList)){
            for(FacilityMaintainSnap facilityMaintainSnap : facilityMaintainSnapList){
                if(facilityMaintainSnap.getMaintainOrder()!=null&&!facilityMaintainSnap.getMaintainOrder().isDeleteStatus()){
                    if(StringUtils.isBlank(orderIds)){
                        orderIds += facilityMaintainSnap.getMaintainOrder().getId()+"";
                    }else{
                        orderIds +=","+facilityMaintainSnap.getMaintainOrder().getId();
                    }
                }
            }
        }
        if(StringUtils.isNotBlank(orderIds)){
            QueryParam queryParam1 = new QueryParam(pageIndexParam,pageSizeParam);
            queryParam1.getSqlMap().put("idIn",orderIds);
            List<MaintainOrder> maintainOrderList = maintainOrderBiz.findList(queryParam1);
            if(CollectionUtils.isNotEmpty(maintainOrderList)){
                for(MaintainOrder maintainOrder : maintainOrderList){
                    JSONObject jsonObject = maintainOrder.toJSONObject();
                    JSONArray tags = new JSONArray();
                    JSONObject tag;
                    if (maintainOrder.isOrderType()) {
                        tag = new JSONObject();
                        tag.put("color", "blue");
                        tag.put("name", "一次性");
                        tags.add(tag);
                    } else {
                        tag = new JSONObject();
                        tag.put("name", "周期性");
                        tag.put("color", "blue");
                        tags.add(tag);
                    }
                    if (null != maintainOrder.getOrderAssignTypeEnum()) {
                        tag = new JSONObject();
                        tag.put("color", "blue");
                        tag.put("name", "被指派");
                        tags.add(tag);
                    }
                    /*****判断是否逾期和异常******/
                    if (!maintainOrder.getOrderStatusEnum().getCode().equals("WAIT_PULISHING") && !maintainOrder.getOrderStatusEnum().getCode().equals("WAIT_TAKING")) {
                        if (maintainOrder.getOrderStatusEnum().getCode().equals("WAIT_PRESENCE") || maintainOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")) {
                            if (maintainOrder.getDelayRealTime().before(new Date())) {
                                tag = new JSONObject();
                                tag.put("color", "blue");
                                tag.put("name", "逾期");
                                tags.add(tag);
                            }
                        } else if (maintainOrder.getOrderStatusEnum().getCode().equals("IN_AUDITING") || maintainOrder.getOrderStatusEnum().getCode().equals("COMPLETED")) {
                            if (null != maintainOrder.getFinishTime()) {
                                if (maintainOrder.getDelayRealTime().before(maintainOrder.getFinishTime())) {
                                    tag = new JSONObject();
                                    tag.put("color", "blue");
                                    tag.put("name", "逾期");
                                    tags.add(tag);
                                }
                            }
                        }
                        if (maintainOrder.isAbnormal()) {
                            tag = new JSONObject();
                            tag.put("color", "red");
                            tag.put("name", "异常");
                            tags.add(tag);
                        }
                    }
                    jsonObject.put("tags", tags);
                    rows.add(jsonObject);
                }
                data.put("rows",rows);
            }
            QueryParam queryParam2 = new QueryParam();
            queryParam2.getSqlMap().put("idIn",orderIds);
            List<MaintainOrder> maintainOrderList2 = maintainOrderBiz.findList(queryParam2);
            if(CollectionUtils.isNotEmpty(maintainOrderList2)){
                data.put("records",maintainOrderList2.size());
            }
        }
        return  ResultUtil.success(data);
    }

    /**
     * 设备的维保记录
     * @param deviceId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/deviceKeeping")
    public ResultDto deviceKeep(String deviceId,String pageIndex,String pageSize){
        String hql = "select obj from MaintainOrder obj where exists( select fm from FacilityMaintainSnap fm where fm.maintainOrder.id=obj.id and obj.deleteStatus =false " +
                "fm.facilityId ="+StringConverters.null2Long(deviceId)+")";
        List<MaintainOrder>maintainOrderList = maintainOrderBiz.hqlExcute(hql,new QueryParam(pageIndex,pageSize));
        JSONArray jsonArray = new JSONArray();
        for(MaintainOrder maintainOrder:maintainOrderList){
            jsonArray.add(maintainOrder.toJSONObject());
        }
        return ResultUtil.success(jsonArray);
    }

    /**
     * 查看工作内容（设备和工艺）接口
     */
    @RequestMapping("/getFacilityAndTechnology")
    @ResponseBody
    public ResultDto getFacilityAndTechnology(String facilityId,String maintainTechnologyId) {
        return maintainOrderBiz.getFacilityAndTechnology(facilityId,maintainTechnologyId);
    }


}
